package com.weimob.demo.admin.security;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.weimob.demo.common.utils.WebUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import lombok.extern.slf4j.Slf4j;

import java.io.PrintWriter;

/**
 * Created by junxiao on 2016/12/31.
 */
@Slf4j
public class MyFormAuthenticationFilter extends FormAuthenticationFilter {

    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
        String username = getUsername(request);
        String password = getPassword(request);
        log.error("token create");
        return  new UsernamePasswordToken(username, password);
    }

    /**
     * 访问被拒(如果未登录跳转到登录，已登录情况下，跳转到未授权url，或者 401)
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        log.debug("Attempting to access a path which requires authentication.  Forwarding to the "
                + "Authentication url [" + getLoginUrl() + "]");
        if (!WebUtils.isAjaxRequest((HttpServletRequest)request)) {// 不是ajax请求
            return super.onAccessDenied(request, response);
        } else {
            response.setCharacterEncoding("UTF-8");
            PrintWriter out = response.getWriter();
            out.println("{message:'login'}");
            out.flush();
            out.close();
            return false;
        }
    }

    /**
     * 登录成功
     * @param token
     * @param subject
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        if (WebUtils.isAjaxRequest((HttpServletRequest)request)) {// 不是ajax请求
            super.onLoginSuccess(token, subject, request, response);
        } else {
            response.setCharacterEncoding("UTF-8");
            PrintWriter out = response.getWriter();
            out.println("{success:true,message:'登入成功'}");
            out.flush();
            out.close();
        }
        return false;
    }

    /**
     * 登录失败
     * @param token
     * @param e
     * @param request
     * @param response
     * @return
     */
    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        log.error("login failure");
        return super.onLoginFailure(token, e, request, response);
//        String className = e.getClass().getName(), message = "";
//        if (IncorrectCredentialsException.class.getName().equals(className)
//                || UnknownAccountException.class.getName().equals(className)){
//            message = "用户或密码错误, 请重试.";
//        } /*else if (e.getMessage() != null && StringUtils.startsWith(e.getMessage(), "msg:")){
//            message = StringUtils.replace(e.getMessage(), "msg:", "");
//        }*/
//        else{
//            message = "系统出现点问题，请稍后再试！";
//            e.printStackTrace(); // 输出到控制台
//        }
//        request.setAttribute(getFailureKeyAttribute(), className);
//        request.setAttribute(getMessageParam(), message);
//        return true;
    }

//    /**
//     * 获取登录用户名
//     */
//    protected String getUsername(ServletRequest request, ServletResponse response) {
//        String username = super.getUsername(request);
//        if (StringUtils.isBlank(username)){
//            username = StringUtils.toString(request.getAttribute(getUsernameParam()), StringUtils.EMPTY);
//        }
//        return username;
//    }
//
//    /**
//     * 获取登录密码
//     */
//    @Override
//    protected String getPassword(ServletRequest request) {
//        String password = super.getPassword(request);
//        if (StringUtils.isBlank(password)){
//            password = StringUtils.toString(request.getAttribute(getPasswordParam()), StringUtils.EMPTY);
//        }
//        return password;
//    }
//
//    /**
//     * 获取记住我
//     */
//    @Override
//    protected boolean isRememberMe(ServletRequest request) {
//        String isRememberMe = WebUtils.getCleanParam(request, getRememberMeParam());
//        if (StringUtils.isBlank(isRememberMe)){
//            isRememberMe = StringUtils.toString(request.getAttribute(getRememberMeParam()), StringUtils.EMPTY);
//        }
//        return StringUtils.toBoolean(isRememberMe);
//    }
}
